﻿using RadarMonitor.DB;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RadarMonitor.ViewModel
{
    // 为了分页显示
    public class AyncLogItemEnumerator : IEnumerable<logItem>, IEnumerator<logItem>
    {

        // 限制只能在创建实例的线程中访问数据。
        private int ThreadId;

        private SqlDataReader reader;

        private SqlConnection connection;



        #region IEnumerable 接口
        // Must implement GetEnumerator, which returns a new StreamReaderEnumerator.
        public IEnumerator<logItem> GetEnumerator()
        {
            if (Thread.CurrentThread.ManagedThreadId == ThreadId)
            {
                return this;
            }
            return null;

        }

        // Must also implement IEnumerable.GetEnumerator, but implement as a private method.
        private IEnumerator GetEnumerator1()
        {
            return this.GetEnumerator();
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator1();
        }

        #endregion

        #region IEnumerator

        logItem _currentAlarm;

        private bool disposedValue;

        //  IEnumerator<logItem>
        logItem IEnumerator<logItem>.Current
        {
            get
            {
                if (Thread.CurrentThread.ManagedThreadId != ThreadId)
                {
                    throw new InvalidOperationException("不支持跨线程访问");
                }
                if (reader == null || _currentAlarm == null)
                {
                    throw new InvalidOperationException();
                }
                return _currentAlarm;
            }
        }

        // IEnumerator
        private object Current1
        {
            get { return (this as IEnumerator<logItem>).Current; }
        }
        object IEnumerator.Current => Current1;


        bool IEnumerator.MoveNext()
        {
            if (Thread.CurrentThread.ManagedThreadId != ThreadId)
            {
                throw new InvalidOperationException("不支持跨线程访问");
            }

            if (reader.Read()) //有数据
            {
                _currentAlarm = new logItem(
                    reader.GetInt32(0),
                    reader.GetInt32(1),
                    reader.GetDateTime(2),
                    reader.GetInt32(3),
                    reader.GetString(4)?.Trim()
                    );
                return true;
            }
            return false; //无数据
        }

        void IEnumerator.Reset()
        {
            throw new InvalidOperationException();
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    if (!reader.IsClosed)
                    {
                        reader.Close();
                    }
                    try
                    {
                        connection.Close();
                    }
                    catch { }
                }

                // TODO: free unmanaged resources (unmanaged objects) and override finalizer
                // TODO: set large fields to null
                disposedValue = true;
            }
        }

        // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
        // ~AyncAlarmEnumerator()
        // {
        //     // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
        //     Dispose(disposing: false);
        // }

        void IDisposable.Dispose()
        {
            // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
            Dispose(disposing: true);
            GC.SuppressFinalize(this);

        }

        #endregion

        /// <summary>
        /// 从数据库中读取一组数据 [StartIndex StartIndex+Length) 左闭右开
        /// </summary>
        /// <param name="startindex">从那个位置开始读；必须>=0 </param>
        /// <param name="length">要读取的长度 > 0 </param>
        public AyncLogItemEnumerator(int startindex ,int length)
        {
            if(startindex <0 || length <= 0)
            {
                throw new InvalidProgramException();
            }

            ThreadId = Thread.CurrentThread.ManagedThreadId;
            var conectionStr = DBHelper.Instance.ConnectionString();
            connection = new SqlConnection(conectionStr);
            connection.Open();

            var sqlStr = $"SELECT * FROM Table_Monidor ORDER BY Id desc OFFSET  {startindex} ROWS FETCH NEXT {length} ROWS ONLY";
            var command = new SqlCommand(sqlStr, connection);
            reader = command.ExecuteReader();
        }


    }
}
